<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElCard, ElRow, ElCol, ElStatistic, ElButton, ElTable, ElTableColumn, ElTag } from 'element-plus'
import { User, Document, Calendar, TrendCharts } from '@element-plus/icons-vue'
import { userApi } from '@/api/modules/user.api'
import { questionApi } from '@/api/modules/question.api'
import { paperApi } from '@/api/modules/paper.api'
import { examApi } from '@/api/modules/exam.api'
import { useRouter } from 'vue-router'
import { useCommonStore } from '@/store/common'

const router = useRouter()

const commonStore = useCommonStore()
commonStore.header = '首页'

// 统计数据
const stats = ref({
  totalUsers: 0,
  totalQuestions: 0,
  totalPapers: 0,
  totalExams: 0
})

// 最近的考试活动
const recentExams = ref<any[]>([])

// 获取统计数据
const fetchStats = async () => {
  try {
    const [usersRes, questionsRes, papersRes, examsRes] = await Promise.all([
      userApi.getUserList({ page: 1, pageSize: 1 }),
      questionApi.getQuestionList({ page: 1, pageSize: 1 }),
      paperApi.getPaperList({ page: 1, pageSize: 1 }),
      examApi.getExamList({ page: 1, pageSize: 1 })
    ])

    stats.value = {
      totalUsers: usersRes.data.total_records,
      totalQuestions: questionsRes.data.total_records,
      totalPapers: papersRes.data.total_records,
      totalExams: examsRes.data.total_records
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取最近的考试活动
const fetchRecentExams = async () => {
  try {
    const response = await examApi.getExamList({ page: 1, pageSize: 5 })
    recentExams.value = response.data.data
  } catch (error) {
    console.error('获取最近考试活动失败:', error)
  }
}

// 获取考试状态
const getExamStatus = (exam: any) => {
  const now = new Date()
  const startTime = new Date(exam.start_time)
  const endTime = new Date(exam.end_time)
  
  if (!exam.is_enabled) return { text: '已禁用', type: 'info' }
  if (now < startTime) return { text: '未开始', type: 'warning' }
  if (now >= startTime && now <= endTime) return { text: '进行中', type: 'success' }
  return { text: '已结束', type: 'info' }
}

// 导航到不同页面
const navigateTo = (path: string) => {
  router.push(path)
}

// 获取试卷名称
const getPaperName = (paper: any) => {
  return typeof paper === 'object' ? paper.paper_name : '未知试卷'
}

onMounted(() => {
  fetchStats()
  fetchRecentExams()
})
</script>

<template>
  <div class="home-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>考试系统管理后台</h2>
      <p>欢迎使用考试系统管理后台，这里是您管理试题、试卷、考试活动的控制中心。</p>
    </div>

    <!-- 统计卡片 -->
    <ElRow :gutter="20" class="stats-row">
      <ElCol :span="6">
        <ElCard class="stat-card" @click="navigateTo('/user')">
          <div class="stat-content">
            <div class="stat-icon user-icon">
              <User />
            </div>
            <div class="stat-info">
              <ElStatistic 
                title="用户总数" 
                :value="stats.totalUsers"
                :value-style="{ color: '#409EFF', fontSize: '24px', fontWeight: 'bold' }"
              />
            </div>
          </div>
        </ElCard>
      </ElCol>

      <ElCol :span="6">
        <ElCard class="stat-card" @click="navigateTo('/question')">
          <div class="stat-content">
            <div class="stat-icon question-icon">
              <Document />
            </div>
            <div class="stat-info">
              <ElStatistic 
                title="试题总数" 
                :value="stats.totalQuestions"
                :value-style="{ color: '#67C23A', fontSize: '24px', fontWeight: 'bold' }"
              />
            </div>
          </div>
        </ElCard>
      </ElCol>

      <ElCol :span="6">
        <ElCard class="stat-card" @click="navigateTo('/paper')">
          <div class="stat-content">
            <div class="stat-icon paper-icon">
              <TrendCharts />
            </div>
            <div class="stat-info">
              <ElStatistic 
                title="试卷总数" 
                :value="stats.totalPapers"
                :value-style="{ color: '#E6A23C', fontSize: '24px', fontWeight: 'bold' }"
              />
            </div>
          </div>
        </ElCard>
      </ElCol>

      <ElCol :span="6">
        <ElCard class="stat-card" @click="navigateTo('/activity')">
          <div class="stat-content">
            <div class="stat-icon exam-icon">
              <Calendar />
            </div>
            <div class="stat-info">
              <ElStatistic 
                title="考试活动" 
                :value="stats.totalExams"
                :value-style="{ color: '#F56C6C', fontSize: '24px', fontWeight: 'bold' }"
              />
            </div>
          </div>
        </ElCard>
      </ElCol>
    </ElRow>

    <!-- 快速操作 -->
    <ElCard class="quick-actions">
      <template #header>
        <h3>快速操作</h3>
      </template>
      <ElRow :gutter="20">
        <ElCol :span="6">
          <ElButton type="primary" size="large" block @click="navigateTo('/question')">
            创建试题
          </ElButton>
        </ElCol>
        <ElCol :span="6">
          <ElButton type="success" size="large" block @click="navigateTo('/paper')">
            创建试卷
          </ElButton>
        </ElCol>
        <ElCol :span="6">
          <ElButton type="warning" size="large" block @click="navigateTo('/activity')">
            创建考试
          </ElButton>
        </ElCol>
        <ElCol :span="6">
          <ElButton type="info" size="large" block @click="navigateTo('/user')">
            用户管理
          </ElButton>
        </ElCol>
      </ElRow>
    </ElCard>

    <!-- 最近的考试活动 -->
    <ElCard class="recent-exams">
      <template #header>
        <div class="card-header">
          <h3>最近的考试活动</h3>
          <ElButton type="primary" size="small" @click="navigateTo('/activity')">
            查看全部
          </ElButton>
        </div>
      </template>
      
      <ElTable :data="recentExams" stripe>
        <ElTableColumn prop="exam_name" label="活动名称" min-width="200" />
        
        <ElTableColumn prop="paper" label="试卷" width="150">
          <template #default="{ row }">
            {{ getPaperName(row.paper) }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="start_time" label="开始时间" width="150">
          <template #default="{ row }">
            {{ new Date(row.start_time).toLocaleString() }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="end_time" label="结束时间" width="150">
          <template #default="{ row }">
            {{ new Date(row.end_time).toLocaleString() }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn label="状态" width="100">
          <template #default="{ row }">
            <ElTag :type="getExamStatus(row).type">
              {{ getExamStatus(row).text }}
            </ElTag>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
  </div>
</template>

<style scoped>
.home-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 16px;
}

.stats-row {
  margin-bottom: 30px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  height: 120px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  font-size: 40px;
  margin-right: 20px;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-icon {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.question-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.paper-icon {
  background: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.exam-icon {
  background: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.stat-info {
  flex: 1;
}

.quick-actions {
  margin-bottom: 30px;
}

.quick-actions h3 {
  margin: 0;
  color: #303133;
}

.recent-exams h3 {
  margin: 0;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-statistic__head) {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}
</style>